package com.cy.teducommunitys.com.common.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author :mdzz
 * @description :
 * @date :2019/7/19 19:28
 */
//@Configuration
@ConfigurationProperties("executor")//表示从配置中读取前缀为executor的数据并set给对应的变量
@Data
@Slf4j
public class SpringAsyncConfig implements AsyncConfigurer {
    @Value("${executor.corePoolSize}")//从配置文件中取值，取不导致就直接赋值默认的10
    private int corePoolSize=10;
    @Value("${executor.maximumPoolSize}")
    private int maximumPoolSize=20;
    @Value("${executor.keepAliveTime}")
    private int keepAliveTime=30;
    @Value("${executor.queueCapacity}")
    private int queueCapacity=20;
    private ThreadFactory threadFactory=new ThreadFactory() {
        private AtomicLong al=new AtomicLong(100);
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "cgb-service-"+al.getAndIncrement());
        }
    };
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setCorePoolSize(corePoolSize);
        pool.setMaxPoolSize(maximumPoolSize);
        pool.setKeepAliveSeconds(keepAliveTime);
        pool.setQueueCapacity(queueCapacity);
        pool.setThreadFactory(threadFactory);
        //设置拒绝执行的处理
        pool.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                log.error("队列满了！");
            }
        });
        pool.initialize();//添加初始化
        return pool;
    }
}
